﻿package net.sapfree.core.web;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import net.sapfree.core.code.Base64;


public class URLProcessor {

	private ParamProcessor m_pp = new ParamProcessor();
	
	/**
	 * 根据当前的请求生成一个串，该串包含当前请求的URL和FORM参数，相当于一个QueryString
	 * @param request  request对象
	 * @param region_filter  过滤要获取的参数名称的正则表达式，生成的查询串中只包含可以用filter_prefix匹配的参数
	 * @return  经过BASE编码的串
	 */
	public String encode(HttpServletRequest request,String region_filter){
		
		Pattern p = null;
		if(region_filter != null && !"".equals(region_filter))
		{
			p = Pattern.compile(region_filter);
		}
		
		String requestURI = request.getRequestURI();
		StringBuffer sb = new StringBuffer();
		sb.append(requestURI);
		
		Enumeration paramEnum = request.getParameterNames();
		if(paramEnum != null && paramEnum.hasMoreElements())
		{
			sb.append("?");
			while(paramEnum.hasMoreElements())
			{
			    String key = (String)paramEnum.nextElement();
			    //过滤掉单点登录验证添加的参数
			    if(p != null && !p.matcher(key).lookingAt()) continue;
			    String values[] = request.getParameterValues(key);
			    for(int i=0;i<values.length;i++){
			    	sb.append(key).append("=").append(encodeParamValue(values[i])).append("&");
			    }
			}
		}
		String string = sb.toString();
		//去除最后一个分隔符
		if(string.endsWith("&")) string = string.substring(0, string.length()-1);
		return encode(string);
	}
	
	private String encodeParamValue(String v)
	{
		return m_pp.paramValueEncode(v);
	}
	
	private  String encode(String backurl){
		return Base64.encode(backurl);
	}
	
	public String decode(String backurl) throws UnsupportedEncodingException{
		return Base64.decode(backurl);
	}	
}
